﻿using HR60_PanelSoft.NetWork.Base;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace HR60_PanelSoft.Tools
{
    class NetUtils
    {
        private static SerialPort _serialPort = new SerialPort();        //全局的串口；

        private static UdpClient _sendClient = null;
        private static IPEndPoint _sendEndpoint = null;

        private static UdpClient _recvClient = null;
        public static IPEndPoint _recvEndpoint = null;

        public static byte[] returnData = null;
        

        static NetUtils()
        {
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived); //订阅委托  

            setSerialPortSetting();


        }


        private static void setSerialPortSetting(){

            _serialPort.WriteBufferSize = 4096;
            _serialPort.ReadBufferSize = 4096;
            _serialPort.BaudRate = 9600;
            _serialPort.DataBits = 8;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Parity = Parity.None;
            _serialPort.ReceivedBytesThreshold = 7;
          
            
        }



        public static void newSendUDPClient(String ip, int port)
        {

            _sendClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));

            _sendClient.EnableBroadcast = true;

            _sendEndpoint = new IPEndPoint(IPAddress.Parse(ip), port);

            _sendClient.Client.SendTimeout = Config.sendTimeout;

            _sendClient.Client.ReceiveTimeout = Config.recvTimeout;
          
        }

     


        public static void newRecvUDPClient(int port)
        {

            _recvClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));

            _recvEndpoint = new IPEndPoint(IPAddress.Any, 0);

            _recvClient.Client.ReceiveTimeout = Config.recvTimeout;
        

        }

        public static void  sendDataByUDP(byte[] data){

            _sendClient.Send(data, data.Length, _sendEndpoint);
          
        }

        public static byte[] recvSendClientUDPData()
        {
            return _sendClient.Receive(ref _recvEndpoint); 
        }

        public static byte[] recvUDPData()
        {
          
            return  _recvClient.Receive(ref _recvEndpoint); 

        }


        public static void releaseRecvUDPClient()
        {
            if (_recvClient != null)
                _recvClient.Close();
        }


        public static void releaseSendUDPClient()
        {
            if (_sendClient != null)
                _sendClient.Close();
        }

        public static void startSerial(string name)
        {
            _serialPort.PortName = name;
            setSerialPortSetting();
            if (!_serialPort.IsOpen)
            {
                _serialPort.Open();
            }

        }


        public static void releaseSerial(string name)
        {
           
            if (_serialPort.IsOpen)
            {
                _serialPort.Close();
            }

        }

        public static void sendDataBySerial(byte[] buf)
        {
            if (!_serialPort.IsOpen)
                throw new Exception("串口未打开");
            returnData = null;//清除所有数据
            _serialPort.Write(buf,0,buf.Length);//写数据

        }

        public static byte[] recvSerialData()
        {
            return returnData;

        }

        static void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (_serialPort.IsOpen) //判断是否串口打开
            {
                byte[] byteRead = new byte[_serialPort.BytesToRead]; //BytesToRead:sp1接收的字符个数

                {
                    try
                    {
                        Byte[] receivedData = new Byte[_serialPort.BytesToRead]; //创建接收字节数组
                        _serialPort.Read(receivedData, 0, receivedData.Length); //读取数据
                        _serialPort.DiscardInBuffer(); //清空SerialPort控件的Buffer
                        string strRcv = null;
                        for (int i = 0; i < receivedData.Length; i++) //窗体显示
                        {

                            strRcv += receivedData[i].ToString("X2") + " "; //16进制显示
                        }
                        LogUils.debug("_serialPort_DataReceived", "接收串口数据：" + strRcv);
                        // 数据每清除之前需拼接原来的数据
                        if (returnData != null && receivedData != null)
                        {
                            returnData = returnData.Concat(receivedData).ToArray();
                        }
                        else if (returnData == null && receivedData != null)
                        {
                            returnData = receivedData;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message, "出错提示");
                        LogUils.error("_serialPort_DataReceived,串口接受错误！！", ex);
                    }
                }
            }
            else
            {
                MessageBox.Show("请打开某个串口", "错误提示");
                LogUils.error("_serialPort_DataReceived", "请打开某个串口错误");
            }

        }






        public static  string[] getComList()
        {

            return System.IO.Ports.SerialPort.GetPortNames();

        }



        public static string getBroadcast(string ipAddress, string subnetMask)
        {

            byte[] ip = IPAddress.Parse(ipAddress).GetAddressBytes();
            byte[] sub = IPAddress.Parse(subnetMask).GetAddressBytes();

            // 广播地址=子网按位求反 再 或IP地址
            for (int i = 0; i < ip.Length; i++)
            {
                ip[i] = (byte)((~sub[i]) | ip[i]);
            }
            return new IPAddress(ip).ToString();
        }



    public    static List<string> getIPAddress()
        {

            List<string> list = new List<string>();
          
                //获取IP地址 

                string st = "";

                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {

                    if ((bool)mo["IPEnabled"] == true)
                    {

                        //st=mo["IpAddress"].ToString(); 

                        System.Array ar;

                        ar = (System.Array)(mo.Properties["IpAddress"].Value);

                        st = ar.GetValue(0).ToString();

                        list.Add(st);

                       

                    }

                }

                moc = null;

                mc = null;


                return list;
    
         
        }

    public static List<string> GetNetMask()
        {

            List<string> list = new List<string>();

            //获取IP地址 

            string st = "";

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {

                if ((bool)mo["IPEnabled"] == true)
                {

                    //st=mo["IpAddress"].ToString(); 

                    System.Array ar;

                    ar = (System.Array)(mo.Properties["IPSubnet"].Value);

                    st = ar.GetValue(0).ToString();

                    list.Add(st);



                }

            }

            moc = null;

            mc = null;


            return list;


        }






    }
}
